package com.gk.panda.apis.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gk.panda.apis.dto.PatrolmanSaveDto;
import com.gk.panda.apis.dto.PatrolmanSearchDto;
import com.gk.panda.apis.mapper.PatrolmanMapper;
import com.gk.panda.apis.service.PatrolmanService;
import com.gk.panda.commons.result.Result;
import com.gk.panda.commons.util.UserUtil;
import com.gk.panda.pojo.Patrolman;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

@Service
public class PatrolmanServiceImpl extends ServiceImpl<PatrolmanMapper, Patrolman> implements PatrolmanService {

    /**
     * 查询巡护人员名称列表
     * @return
     */
    @Override
    public List<String> listPatrolman() {
        int orgId = UserUtil.getCurrentUserOrgId();
        QueryWrapper<Patrolman> wrapper = new QueryWrapper<>();
        wrapper.eq("org_id",orgId);
        Patrolman patrolman = this.getOne(wrapper);
        if (patrolman != null) {
            String[] names = patrolman.getNames().split(",");
            return Arrays.asList(names);
        }
        return null;
    }

    /**
     * 分页查询巡护人员信息列表
     * @param dto
     * @return
     */
    @Override
    public Page<Patrolman> pagePatrolman(PatrolmanSearchDto dto) {
        Page<Patrolman> page = new Page<>(dto.getPageNumber(), dto.getPageSize());
        QueryWrapper<Patrolman> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(dto.getOrgIds())) {
            String[] orgIds = dto.getOrgIds().split(",");
            wrapper.in("org_id",Arrays.asList(orgIds));
        }
        wrapper.like(StringUtils.isNotEmpty(dto.getName()),"names",dto.getName());
        return this.page(page,wrapper);
    }

    /**
     * 添加巡护人员信息
     * @param dto
     * @return
     */
    @Override
    public Result<String> addPatrolman(PatrolmanSaveDto dto) {
        QueryWrapper<Patrolman> wrapper = new QueryWrapper<>();
        wrapper.eq("org_id",dto.getOrgId());
        Patrolman dbPatrolman = this.getOne(wrapper);
        if (dbPatrolman != null) return Result.write(201,"已有此机构人员信息，请直接修改");
        Patrolman patrolman = new Patrolman();
        patrolman.setOrgId(dto.getOrgId());
        patrolman.setNumber(dto.getNumber());
        patrolman.setNames(dto.getNames());
        boolean save = this.save(patrolman);
        if (save) return Result.write(200,"添加成功");
        return Result.write(201,"添加出错");
    }
}
